package com.example.controller;

import com.example.config.ResponseEntity;
import com.example.entity.BackendApi;
import com.example.service.BackendApiService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
@CrossOrigin
public class BackendApiController {

    @Autowired
    BackendApiService backendApiService;

    @RequestMapping("/getall")
    public ResponseEntity getApis(){
        return ResponseEntity.success(backendApiService.getApis());
    }
    
    @GetMapping("/page")
    public ResponseEntity getApisPage(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String orderBy) {
        PageInfo<BackendApi> pageInfo = backendApiService.getApisPage(pageNum, pageSize, orderBy);
        return ResponseEntity.success(pageInfo);
    }
    
    @GetMapping("/search")
    public ResponseEntity searchApis(
            @RequestParam String name,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        PageInfo<BackendApi> pageInfo = backendApiService.searchApisByName(name, pageNum, pageSize);
        return ResponseEntity.success(pageInfo);
    }
    
    @GetMapping("/getById/{id}")
    public ResponseEntity getApiById(@PathVariable int id) {
        BackendApi backendApi = backendApiService.getApiById(id);
        if (backendApi != null) {
            return ResponseEntity.success(backendApi);
        } else {
            return ResponseEntity.error("API不存在");
        }
    }
    
    @PostMapping("/save")
    public ResponseEntity saveApi(@RequestBody BackendApi backendApi) {
        boolean result = backendApiService.saveApi(backendApi);
        if (result) {
            return ResponseEntity.success(null);
        } else {
            return ResponseEntity.error("保存失败");
        }
    }
    
    @DeleteMapping("/delete/{id}")
    public ResponseEntity deleteApi(@PathVariable int id) {
        boolean result = backendApiService.deleteApi(id);
        if (result) {
            return ResponseEntity.success(null);
        } else {
            return ResponseEntity.error("删除失败");
        }
    }
}
